package com.star.robot.service;

import com.star.robot.constant.Constant;
import com.star.robot.dto.RegRequestDto;
import com.star.robot.dto.ResultDto;
import com.star.robot.entity.Company;
import com.star.robot.entity.User;
import com.star.robot.repository.CompanyRepository;
import com.star.robot.repository.UserRepositoty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserRepositoty userRepositoty;

    @Autowired
    private CompanyRepository companyRepository;
    /**
     *
     * @return　手机号
     */
    public String getCurrentUsername(HttpServletRequest request){
        User currentUser = getCurrentUser(request);
        return currentUser  == null ? null : currentUser.getPhone().toString();
    }

    public User getCurrentUser(HttpServletRequest request){
        Object currentUser = request.getSession().getAttribute(Constant.CURRENTUSER);
        if(currentUser != null){
            return (User)currentUser;
        }
        return null;
    }

    public Boolean isUser(HttpServletRequest request){
        return  getCurrentUser(request) != null;
    }


    public ResultDto reg(RegRequestDto regRequestDto, HttpServletRequest request) {
        User user=new User();
        user.setPasswd(regRequestDto.getPasswd());
        user.setPhone(regRequestDto.getPhone());
        user.setCityId(regRequestDto.getCityId());
        user.setProvinceId(regRequestDto.getProvinceId());


        Company company=new Company();
        company.setStatus(true);
        company.setCityId(regRequestDto.getCityId());
        company.setProvinceId(regRequestDto.getProvinceId());
        company.setCreateTime(new Date());
        company.setCompanyType(regRequestDto.getCompanyType());
        company.setName(regRequestDto.getCompanyName());

        companyRepository.save(company);

        user.setCompany(company);

        userRepositoty.save(user);

//        company.setUser(user);
//        companyRepository.save(company);

        return ResultDto.builder().build();
    }
}
